package logic

import (
	"context"
	"housing/models/mysql"

	"housing/houserpc/houserpc"
	"housing/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HouseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHouseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HouseListLogic {
	return &HouseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HouseListLogic) HouseList(in *houserpc.HouseListRequest) (*houserpc.HouseListResponse, error) {
	// todo: add your logic here and delete this line

	offset := (in.Page - 1) * in.Size
	var house []mysql.House

	var houseList []*houserpc.HouseList
	tx := mysql.DB.Debug().Offset(int(offset)).Limit(int(in.Size))

	if in.PriceOrder == 1 {
		tx = tx.Order("price desc")
	}

	if in.PriceOrder == 2 {
		tx = tx.Order("price asc")
	}

	if in.TimeOrder == 1 {
		tx = tx.Order("created_at desc")
	}

	if in.TimeOrder == 2 {
		tx = tx.Order("created_at asc")
	}
	tx.Find(&house)
	for _, m := range house {
		list := houserpc.HouseList{
			HouseId:  int64(m.ID),
			Title:    m.Title,
			Price:    float32(m.Price),
			Describe: m.Describe,
			Address:  m.Address,
		}
		houseList = append(houseList, &list)
	}
	return &houserpc.HouseListResponse{
		List: houseList,
	}, nil
}
